package com.example.Lezedata.dataModel;

import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bid.Bid;
import common.Common;

public class UserInfoManager {
    private static UserInfoManager manager;
    private static HashMap<String, Bid.UserInfo> userInfoHashMap = new HashMap<String,Bid.UserInfo>();

    public interface OnLoadListDataComplete{
        void listInfoResponse(List<Bid.UserInfo> userInfoList);
    }

    public interface OnLoadDataComplete{
        void infoResponse(Bid.UserInfo userInfo);
    }

    public BidDetailManager.OnLoadListDataComplete onLoadListDataComplete;
    public BidDetailManager.OnLoadDataComplete onLoadDataComplete;

    public static UserInfoManager sharedManager(){
        if (manager == null){
            manager = new UserInfoManager();
        }
        return manager;
    }

    public static void getUserInfoForIds(List<String> ids, final UserInfoManager.OnLoadListDataComplete complete){
        Common.IdList list = Common.IdList.newBuilder().addAllList(ids).build();

        GBNetRequest.stub().batchGetUserInfo(list,
                ServerResponseObserver.observer(new ServerResponseObserver.requestListener<Bid.BatchGetUserInfoResponse>() {
                    @Override
                    public void complete(Bid.BatchGetUserInfoResponse value, GBError error) {
                        if (error == null){
                            if (complete != null){
                                complete.listInfoResponse(value.getListList());
                                for (Bid.UserInfo userInfo:value.getListList()
                                ) {
                                    userInfoHashMap.put(userInfo.getUserId(),userInfo);
                                }
                            }
                        }
                    }
                }));
    }

    public static void getUserInfoForId(String id,final UserInfoManager.OnLoadDataComplete complete){
        if (id == null){
            return;
        }
        final Bid.UserInfo goodsInfo = userInfoHashMap.get(id);
        if (goodsInfo != null){
            if (complete != null) {
                complete.infoResponse(goodsInfo);
            }
            return;
        }
        ArrayList<String> list = new ArrayList<String>();
        list.add(id);
        getUserInfoForIds(list, new UserInfoManager.OnLoadListDataComplete() {
            @Override
            public void listInfoResponse(List<Bid.UserInfo> userInfoList) {
                if (complete != null) {
                    if (userInfoList.size() > 0){
                        complete.infoResponse(userInfoList.get(0));
                    }
                }
            }
        });
    }
}
